3.4 Node.js (v18.19.1 on Ubuntu 24.04.04) - [server-side] JavaScript Runtime Environment

  1. Motivations
    • To support applications that use many asynchronous i/o and real-time communications
    • To support NoSQL database systems, such as MongoDB
    • To support WebSocket
    • To support web sevices
    • Node.js (JavaScript runtime environment at the server-side) as a server-side script language, such as PHP

  2. Project TRU Web Server with JavaScript (TRUWSJS) in Section 5.1
    • Web server system with Node.js that suppots
      • Fetching non-program files
      • Execution of server-side JavaScript files

  3. Learning objectives
    • Understanding and use of callback functions and Promises for non-blocking/asynchronous operations
    • Understanding of event-driven programming
    • Use of ES6 especially for non-blocking/asynchronouse operations
    • Use of server-side JavaScript run-time environment with modules, i.e., Node.js

  4. Prerequisites not only for this section but also for all the other chapters and sections
    • JavaScript - AJAX, event driven programming with callback functions
    • [jQuery]
    • The Linux environment, e.g., Ubuntu
    • PuTTY, your account in cs.tru.ca, or your Ubuntu computer; Online Node.js compilers are not convenient because you need to access the system.
    • Basic of the command line interface (CLI) in the Linux environment
    • [A text editor, such as 'nano' and 'vi', in the Linux environment]

  5. What is Node.js?
    • Introduction to Node.js - Read the first three paragraphs in Node.js
      • What are the common application areas?
        Web applications with many i/o operations, and real-time web applications
      • How do you want to define what Node.js is?
    • Read the first page in PHP vs. Node.js
      • How are PHP and Node.js different?
      • What problems does PHP have?
      • What does 'Node.js is functionally similar to the PHP + Apache or ASP + IIS stacks.' mean?
      • How is Node.js different from other frameworks?
    • What does Node.js do?
      • In order to run JavaScript in the backend, it needs to be interpreted and executed.
      • This is what Node.js does, by making use of Google's V8 VM that is the same runtime environment for JavaScript in Chrome.
      • Node.js provides with a lot of useful modules which are considered as libraries, so that you do not have to write everything from scratch.
      • Node.js is a runtime environment that includes libraries.
      • There are also many useful frameworks around Node.js. For example, Express.js.
    • Comparison of client-side JavaScript and server-side JavaScript Node.js
      Underlying PlatformTypeResponsibility# of files in a programLibrariesEtc
      Server-side (Node.js) Operating system Standalone program;
      Built-in web server module and other modules
      General purpose programming;
      Event-driven programming;
      To access server-side resources
      Usually several Required or imported from other modules(, i.e., files) Variables must be declared with let, var, and const.
      Client-side Web browser A part of a web program Event-driven programming;
      To access/manipulate HTML elements responding to events, such as mouse related and keyboard related events;
      To communicate with other programs running on other computers
      Usually one Linked within <script> tag Variables can be used without declaration with let, var, and const.
    • Read all in Node.js Modules (and JavaScript Modules).
      • What is a module?
      • What modules? Read Node.js Built-in Modules.
        Some built-in modules such as http, https, cluster, fs, path, querystring, and url are very useful.
        They are the APIs that we study and use for the class projects.
      • Comparison
        TypeExplanationKeywords
        CommonJS modules Default in Node.js; Developped before ES modules exports ..., require(...)
        ECMAScript (ES) modules JavaScript standard modules export [default] ..., import ... from
        You may read something more from CommonJS vs. ES modules in Node.js.
      • hello1.js as a module. (Note that each JS file is a module.) We can export multiple functions.
        // hello1.js
        exports.hello = function() {
            console.log('Hello World!');
        }
        // main1.js
        const helloooo = require('./hello1');  // Not hello1.js? 
                                             // When there is no file extension, .js is assumed. 
                                             // Obviously you can also use a full filename, even with a different file extension.
                                             // require() returns an object having the property in 'exports' object from './hello1.js'.
        helloooo.hello();
        //-- at server ----------------------------------------
        $ node main1.js
        
      • Trial 1. Let's login cs.tru.ca and try the above code.
        Do you remember any text editor on Ubuntu?
        nano or vi on PuTTY terminal; or editing with WinSCP and execute commands on Command Terminal with WinSCP; or editing with WinSCP and executing commands on PuTTY terminal. Note that there is a button on WinSCP to open PuTTY terminal.
      • hello2.js as a module in a different way. A module is exported as a function.
        // hello2.js
        module.exports = function() {
            console.log('Hello World!');
        }
        // main2.js
        const helloooo = require('./hello2');
        helloooo();
        //-- at server ----------------------------------------
        $ node main2.js
        
      • Trial 2. Try the above code on cs.tru.ca.
      • Module and it's directory with index.js
        const helloooo = require('./hello2');  // ./hello2.js or ./hello2/index.js
        
      • Can you use a differnt file extension? For example, hello2.sjs and main2.sjs. You can try with the above example.
      • Differences between require/exports and import/export, in Node.js
        Default file extensionExamples
        CommonJS modules with require/exports.jsSee the examples in Trial 1 and 2.
        ES modules with import/export.mjs
        (or .js with package.json that includes "type":"module")
        // test_export.mjs
        let age = 20;
        let name = 'John';
        const print = () => { return `${name}'s age is ${age}.`; }
        export {age, name, print};
        
        // test_import.mjs
        import {print} from "./test_export.mjs";
        console.log(print());
        
      • Trial 3. Try the example in the above table on cs.tru.ca. You should use ES modules.

  6. How to install Node.js?
    • On Ubuntu (We will focus on Ubuntu, not Windows.)
      $ sudo apt-get update
      $ sudo apt-get install nodejs
      $ sudo apt-get install npm
      
    • On Windows?
      https://nodejs.org/en/download/
      
    • npm is a Node.js package manager. It is used to install other Node.js modules.

  7. How to install a web server with Node.js?
    • There is a simple zero-configuration command-line http server - http-server.
    • $ npm install http-server
      
    • Even though the above http-server is not for production usage, it is good for study. But we can develop a HTTP server ourselves in the next chapter. There are many web sites explaining how to develop a simple HTTP server that can be used for our study.

  8. How to display 'Hello World!' with Node.js and the built-in http module?
    • Read 'Hello World Tutorial' in Node.js Get Started
      • hello.js - to print 'Hello World' on a console
        // hello.js
        console.log('Hello World!');
        //-- at server ----------------------------------------
        $ node hello.js
        
      • Trial 4. Connect to cs.tru.ca with your account, edit the next hello.js with your port number, not 8080, and run it.
      • hello_http.js - to print 'Hello World' from a web browser using the port number 8080
        // hello_http.js
        const http = require('http');  // Require 'http' module; We will study it in detail in the next section.
        const server = http.createServer((req, res) => {  // HTTP server object to deal with HTTP requests from clients
            res.writeHead(200);  // Sends the head to the client with the reponse number 200
            res.end('Hello World!');  // Sends the message back to the client
        });
        server.listen(8080);  // The server listens to the port number 8080.
        //-- at server ----------------------------------------
        $ node hello_http.js
        //-- from a browser on a client -----------------------------------------
        http://cs.tru.ca:8080
        // Browsers usually try to use https, not http, and the above URL may not be reachable.
        // You can try to use 198.162.21.132 instead of cs.tru.ca.
        
      • Trial 5. Connect to cs.tru.ca with your account, edit the next hello_http.js with your port number, not 8080, and run it.
      • How to stop the running node app?
        CTRL-C
      • What command is used to run Node.js?
      • What is a port number?
      • In the above example, is index.html assumed? What is happening here?
      • Trial 5.5 Can you convert the files so that ES modules are used?

  9. References for further information